package com.kxf.androidtestdemo.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kxf.androidtestdemo.R;
import com.kxf.androidtestdemo.bean.User;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

public class OkHttpActivity extends AppCompatActivity {

    private static final String urlPath = "https://www.baidu.com/";
    private TextView tv_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);

        tv_info = findViewById(R.id.tv_info);
    }

    public void getDatasync() {
        try {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
            Request request = new Request.Builder()
                    .url(urlPath + "WebTest/UserServlet")//请求接口。如果需要传参拼接到接口后面。
                    .build();//创建Request 对象
            Response response = null;
            Log.d("kxf", "开始请求");
            response = client.newCall(request).execute();//得到Response 对象
            Log.d("kxf", "response==" + response);
            if (response.isSuccessful()) {
                Log.d("kxf", "response.code()==" + response.code());
                Log.d("kxf", "response.message()==" + response.message());
                Log.d("kxf", "res==" + response.body().string());
                //此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



    }


    public void onClickGetSync(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getDatasync();
            }
        }).start();

    }

    public void onClickGetEnqueue(View view) {
        Log.d("kxf", "Thread.currentThread().getName()==" + Thread.currentThread().getName());

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
                .url(urlPath + "WebTest/UserServlet")
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("kxf", "", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("kxf", "Thread.currentThread().getName()==" + Thread.currentThread().getName());
                Log.d("kxf", "response.code()==" + response.code());
                Log.d("kxf", "response.message()==" + response.message());
                Log.d("kxf", "res==" + response.body().string());
            }
        });
    }

    public void onClickPostSync(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(5, TimeUnit.SECONDS)
                            .readTimeout(10, TimeUnit.SECONDS)
                            .build();//创建OkHttpClient对象
                    MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
                    User u = new User();
                    u.setName("aaa");
                    u.setAge(12);
                    String json = new Gson().toJson(u);
                    RequestBody body = FormBody.create(jsonType, json);
                    Request request = new Request.Builder()
                            .url(urlPath + "WebTest/UserServlet")//请求接口。如果需要传参拼接到接口后面。
                            .post(body)
                            .build();//创建Request 对象
                    Response response = null;
                    Log.d("kxf", "onClickPostSync开始请求");
                    response = client.newCall(request).execute();//得到Response 对象
                    Log.d("kxf", "response==" + response);
                    if (response.isSuccessful()) {
                        Log.d("kxf", "response.code()==" + response.code());
                        Log.d("kxf", "response.message()==" + response.message());
                        Log.d("kxf", "res==" + response.body().string());
                        //此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void onClickPostEnqueue(View view) {
        Log.d("kxf", "Thread.currentThread().getName()==" + Thread.currentThread().getName());

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Log.d("kxf", "intercept 拦截器 Thread.currentThread().getName()==" + Thread.currentThread().getName());
                        return chain.proceed(chain.request());
                    }
                })
                .build();

        MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        User u = new User();
        u.setName("aaa");
        u.setAge(12);
        String json = new Gson().toJson(u);
        RequestBody body = FormBody.create(jsonType, json);
        //创建一个Request
        final Request request = new Request.Builder()
                .url(urlPath + "WebTest/UserServlet")
                .post(body)
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("kxf", "Thread.currentThread().getName()==" + Thread.currentThread().getName());
                Log.e("kxf", "", e);
                call.cancel();
                getDatasync();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("kxf", "Thread.currentThread().getName()==" + Thread.currentThread().getName());
                Log.d("kxf", "response.code()==" + response.code());
                Log.d("kxf", "response.message()==" + response.message());
                Log.d("kxf", "res==" + response.body().string());
            }
        });
    }
}
